package com.example.springcloud.gateway.filter;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName : CheckTokenFilter
 * @Description : 校验Token的全部Filter
 * @Author : tianshuo
 * @Date: 2021-05-17 22:28
 */
@Order(-2)
@Component
public class CheckIpFilter implements GlobalFilter {
    private static final Logger logger = LoggerFactory.getLogger(CheckIpFilter.class);
    private static final String WARNING_MSG = "黑名单限制";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        ServerHttpResponse response = exchange.getResponse();
        String ip = getIp(headers);
        if (ip.equals("127.0.0.1")) {
            logger.info("黑名单限制 ,{}", ip);

            byte[] bits = WARNING_MSG.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
    }

    private String getIp(HttpHeaders headers) {
        return headers.getHost().getHostName();
    }
}

